package com.telchina.common.controller;

import com.telchina.common.annotation.Log;
import com.telchina.common.config.TelchinaConfig;
import com.telchina.common.constant.Constants;
import com.telchina.common.core.controller.BaseController;
import com.telchina.common.core.domain.AjaxResult;
import com.telchina.common.domain.WoAttachment;
import com.telchina.common.enums.BusinessType;
import com.telchina.common.service.IWoAttachmentService;
import com.telchina.common.utils.StringUtils;
import com.telchina.common.utils.file.FileUploadUtils;
import com.telchina.common.utils.file.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

/**
 * 附件管理Controller
 *
 * @author konghao
 * @date 2023-02-21
 */
@RestController
@RequestMapping("/common/attachment")
public class WoAttachmentController extends BaseController {
    @Autowired
    private IWoAttachmentService woAttachmentService;


    /**
     * 分页查询附件管理列表
     */
    // @PreAuthorize("@ss.hasPermi('workorder:attachment:list')")
    @GetMapping("/list")
    public AjaxResult list(WoAttachment woAttachment) {
//        IPage<WoAttachment> list = woAttachmentService.selectList(startPage(), woAttachment);
        List<WoAttachment> list = woAttachmentService.selectListAll(woAttachment);
        return AjaxResult.success(list);
    }

    /**
     * 查询附件管理列表
     */
    // @PreAuthorize("@ss.hasPermi('workorder:attachment:list')")
    @GetMapping("/list/all")
    public AjaxResult listAll(WoAttachment woAttachment) {
        List<WoAttachment> list = woAttachmentService.selectListAll(woAttachment);
        return AjaxResult.success(list);
    }


    /**
     * 获取附件管理详细信息
     */
    // @PreAuthorize("@ss.hasPermi('workorder:attachment:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(woAttachmentService.selectById(id));
    }

    /**
     * 文件上传并保存到附件信息表
     */
    // @PreAuthorize("@ss.hasPermi('workorder:attachment:add')")
    @Log(title = "文件上传", businessType = BusinessType.INSERT)
    @PostMapping(value = "/add")///{bussId}/{bussKey} @PathVariable
    public AjaxResult add(@RequestBody MultipartFile[] files, String bussId, String bussKey, String[] uid) {
        // 先进行文件上传
        if (files.length <= 0) {
            return AjaxResult.error("文件列表为空");
        }
        List<WoAttachment> woAttachments = new ArrayList<>();
        // 进行文件上传并返回附件列表
        try {
            for (int i = 0; i < files.length; i++) {
                MultipartFile multipartFile = files[i];
                String fileName = FileUploadUtils.upload(TelchinaConfig.getUploadPath(), multipartFile);
                // 封装附件信息并返回数据
                int finalI = i;
                WoAttachment woAttachment = new WoAttachment() {{
                    setBussId(bussId);
                    setBussKey(bussKey);
                    setFileName(multipartFile.getOriginalFilename());
                    setFullPath(TelchinaConfig.getUploadPath() + fileName);
                    setPath(fileName);
                    setUid(uid[finalI]);
                    setSize(String.valueOf(multipartFile.getSize()));
                    setSuffix(FilenameUtils.getExtension(multipartFile.getOriginalFilename()));
                }};
                woAttachments.add(woAttachment);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return woAttachmentService.insert(woAttachments) > 0 ? AjaxResult.success(woAttachments) : AjaxResult.error();
    }

    /**
     * 下载文件
     */
    @GetMapping(value = "/download/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
        // 获取附件信息
        WoAttachment woAttachment = woAttachmentService.selectById(id);
        if (woAttachment != null) {
            try {
                if (!FileUtils.checkAllowDownload(woAttachment.getPath()))
                    throw new Exception(StringUtils.format("资源文件()非法，不允许下载。 ", woAttachment.getPath()));

                // 本地资源路径
                String localPath = TelchinaConfig.getProfile();
                // 数据库资源地址
                String downloadPath = localPath + StringUtils.substringAfter(woAttachment.getPath(), Constants.RESOURCE_PREFIX);
                // 下载名称
                String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
                response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                if (!woAttachment.getFileName().equals("") && woAttachment.getFileName() != null)
                    FileUtils.setAttachmentResponseHeader(response, woAttachment.getFileName());
                else
                    FileUtils.setAttachmentResponseHeader(response, downloadName);

                FileUtils.writeBytes(downloadPath, response.getOutputStream());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 删除附件管理
     */
    // @PreAuthorize("@ss.hasPermi('workorder:attachment:remove')")
    @Log(title = "附件管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return woAttachmentService.deleteByIds(ids);
    }
}
